
#include "cocos2d.h"
#include <numeric>

#include "AnimationMng.h"
#include "Common\Exd\EXData.h"

#include "CmdDef.h"

using namespace cocos2d;


AnimationMng::AnimationMng()
{

}



AnimationMng::~AnimationMng()
{

}


void AnimationMng::LoadAnimation(int ID)
{
	dn::EXD_Line_Animations* line = dn::GT_Animations->find(ID);

	size_t frameCount = line->FrameSequence.size();
	if(frameCount == 0) return;

	const std::string& resName = line->ResourceName;
	
	std::set<std::string>::iterator resIt = loadedResources.find(resName);
	if(resIt == loadedResources.end()){
		loadedResources.insert(resName);
		std::string resNameAndSuffix = resName + AnimationResSuffix;
		CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile(resNameAndSuffix.c_str());
	}

	CCArray* pArray=CCArray::createWithCapacity(frameCount);
	for(size_t i=0; i<frameCount; i++){
		const std::string& frameName = line->FrameSequence[i];

		CCSpriteFrame* frame=CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(frameName.c_str());

		pArray->addObject(frame);   
	}

	float delay = line->Delay;
	if( delay < std::numeric_limits<float>::epsilon() ){
		delay = 0.001f;
	}

	CCAnimation* animation = CCAnimation::createWithSpriteFrames(pArray, delay);

	char idxStr[animIdxStrMax];
	sprintf(idxStr, "%d", ID);
	CCAnimationCache::sharedAnimationCache()->addAnimation(animation, idxStr);

	animations.insert( std::make_pair(ID, idxStr) );

}


CCAnimation* AnimationMng::GetAnimation(int ID)
{
	std::map<int, std::string>::iterator it = animations.find(ID);
	if(it != animations.end()){
		const std::string& idxStr = it->second;

		return CCAnimationCache::sharedAnimationCache()->animationByName(idxStr.c_str());
	}

	return 0;

}

